package com.wswy.wzcx.ui.activity;

import android.Manifest;
import android.Manifest.permission;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.che.libcommon.ui.BaseActivity;
import com.facebook.drawee.drawable.ScalingUtils.ScaleType;
import com.facebook.drawee.view.SimpleDraweeView;
import com.qq.e.comm.util.AdError;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.home.RouterUtils;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.MessageCenter;
import com.wswy.wzcx.module.ScTimes;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.dialog.PermissionHintDialog;
import com.wswy.wzcx.ui.dialog.WarningDialog;
import com.wswy.wzcx.utils.DownloadUtils;

import java.util.ArrayList;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import timber.log.Timber;

/**
 * Created by wangduheng26 on 2018/2/1.
 * wangduheng26@gmail.com
 * * 在调用SDK之前，如果您的App的targetSDKVersion >= 23，
 * 那么一定要把"READ_PHONE_STATE"、
 * "WRITE_EXTERNAL_STORAGE"、
 * "ACCESS_FINE_LOCATION"这几个权限申请到，否则SDK将不会工作。
 */

public class SplashActivity extends BaseActivity implements ISplashView {

    private static final String TAG = "SplashActivity";

    private ViewGroup container;
    private TextView skipView;

    private View flBottom;
    private View adTTHint;

    private static final String SKIP_TEXT = "点击跳过 %d";

    private boolean canJump = false;

    private boolean delayJump = false;

    private SplashPresenter mPresenter;

    private boolean nextCheck = false;

    private ImageView bottomLogo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        try {
            //检查更新
            MessageCenter.INSTANCE.mainCheckUpgrade(true);
            StatService.start(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        container = this.findViewById(R.id.splash_container);
        skipView = findViewById(R.id.skip_view);

        flBottom = findViewById(R.id.fl_imgs_container);
        adTTHint = findViewById(R.id.img_ad_hint);
        bottomLogo = findViewById(R.id.img_splash_logo);

//        splashHolder = (ImageView) findViewById(R.id.splash_holder);
//        imgBrand = findViewById(R.id.img_brand);

        mPresenter = new SplashPresenter(this);
        mPresenter.onCreate(getIntent());

        skipView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPresenter.isTTAD()) {
                    StatTools.sendClick(AppContext.getContext(), StatisticsId.ad_splash_csj_skip);
                }
                mPresenter.cancelTrack();
                canJump = true;
                next();
            }
        });

        if (TextUtils.equals(ChannelManager.getChannel(), "huawei")) {
           // bottomLogo.setImageResource(R.drawable.launcher_logo_huawei);
        } else {
          //  bottomLogo.setImageResource(R.drawable.splash_logo);
        }
//        if (!TextUtils.equals(ChannelManager.getChannel(),"mi")){
//            bottomLogo.setOnClickListener(new OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    StatTools.sendClick(AppContext.getContext(),StatisticsId.ad_splash_bottom_logo);
//                }
//            });
//        }

        if (!GlobalConfigManager.getInstance().getSysConf().isEnableBottomClick()) {
            flBottom.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    StatTools.sendClick(AppContext.getContext(), StatisticsId.ad_splash_bottom_logo);
                }
            });
        }
//        if(BuildConfig.DEBUG){
//            canJump = true;
//            next();
//            return;
//        }
        // 如果targetSDKVersion >= 23，就要申请好权限。如果您的App没有适配到Android6.0（即targetSDKVersion < 23），那么只需要在这里直接调用fetchSplashAD接口。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkAndRequestPermission();
        } else {
            // 如果是Android6.0以下的机器，默认在安装时获得了所有权限，可以直接调用SDK
            mPresenter.requestAD();
//            getAd();
        }

    }

//    public void getAd() {
//        String syLogout = GlobalConfigManager.getInstance().getSysConf().getSyLogout().getValue();
//        if (!TextUtils.isEmpty(syLogout) && syLogout.equals("0")) {
//            mPresenter.requestAD();
//        } else {
//            mPresenter.requestNoAd();
//        }
////            container.setVisibility(View.VISIBLE);
////            container.setBackgroundColor(Color.WHITE);
////            flBottom.setVisibility(View.VISIBLE);
////            onShowAd();
////            mPresenter.cancelTrack();
////            canJump = true;
////            next();
//    }

    /**
     * ----------非常重要----------
     * <p>
     * Android6.0以上的权限适配简单示例：
     * <p>
     * 如果targetSDKVersion >= 23，那么必须要申请到所需要的权限，再调用广点通SDK，否则广点通SDK不会工作。
     * <p>
     * Demo代码里是一个基本的权限申请示例，请开发者根据自己的场景合理地编写这部分代码来实现权限申请。
     * 注意：下面的`checkSelfPermission`和`requestPermissions`方法都是在Android6.0的SDK中增加的API，如果您的App还没有适配到Android6.0以上，则不需要调用这些方法，直接调用广点通SDK即可。
     */
    @SuppressLint("CheckResult")
    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        final List<String> lackedPermission = new ArrayList<>();
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }
        if ((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        //位置可选
        if (!lackedPermission.isEmpty() && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            mPresenter.requestAD();
//            getAd();
        } else {
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            doRequestPermissions(lackedPermission, true);
        }
    }

    @SuppressLint("CheckResult")
    @RequiresApi(api = VERSION_CODES.M)
    private void doRequestPermissions(final List<String> lackedPermission, final boolean fromCheck) {
        //弹窗显示
        new PermissionHintDialog(this, lackedPermission, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                String[] requestPermissions = new String[lackedPermission.size()];
                lackedPermission.toArray(requestPermissions);
                requestPermissions(requestPermissions, 1024);
                return null;
            }
        }).show();

    }


    private void showAlertToOpenPermission(String title, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        nextCheck = true;

                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
        builder.show();
    }

    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    @RequiresApi(api = VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024) {
            if (hasAllPermissionsGranted(grantResults)) {
                mPresenter.requestAD();
//                getAd();
            } else {
                // 如果用户没有授权，那么应该说明意图，引导用户去设置里面授权。
                List<String> perms = new ArrayList<>(permissions.length);
                boolean neverShow = false;
                String shouldShowPermission = null;

                for (int i = 0; i < permissions.length; i++) {

                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        perms.add(permissions[i]);
                    }

                    Timber.e("onRequestPermissionsResult --> shouldShowRequestPermissionRationale " + permissions[i] + "     " + shouldShowRequestPermissionRationale(permissions[i]));

                    if (shouldShowPermission == null && !shouldShowRequestPermissionRationale(permissions[i])) {
                        neverShow = true;
                        shouldShowPermission = permissions[i];
                    }
                }

                if (!perms.isEmpty()) {
                    if (perms.size() == 1 && TextUtils.equals(perms.get(0), permission.ACCESS_FINE_LOCATION)) {
                        //只有位置没授权的话 可以通过
                        mPresenter.requestAD();
//                        getAd();
                    } else {
                        //
                        if (shouldShowPermission != null) {
                            switch (shouldShowPermission) {
                                case permission.READ_PHONE_STATE:
                                    showAlertToOpenPermission("请允许获取设备信息权限",
                                            getString(R.string.no_perm_hint,
                                                    getString(R.string.app_name), "设备信息"));
                                    break;
                                case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                                    showAlertToOpenPermission("请允许获取存储空间权限",
                                            getString(R.string.no_perm_hint,
                                                    getString(R.string.app_name), "存储空间"));
                                    break;
                            }
                        } else {
                            doRequestPermissions(perms, false);

                        }


                    }
                }

            }

        }

    }

    @Override
    public void onADPresent() {
        Timber.e("SplashADPresent");
        //splashHolder.setVisibility(View.INVISIBLE); // 广告展示后一定要把预设的开屏图片隐藏起来
        container.setVisibility(View.VISIBLE);
        container.setBackgroundColor(Color.WHITE);
       // flBottom.setVisibility(View.VISIBLE);
        onShowAd();
    }

    @Override
    public void onADClicked() {
        Timber.e("SplashADClicked");
//        String syLogout = GlobalConfigManager.getInstance().getSysConf().getSyLogout().getValue();
//        if (!TextUtils.isEmpty(syLogout) && syLogout.equals("1")) {
//            getDialogTip();
//            mPresenter.getGDT()
//        }
    }

    /**
     * 倒计时回调，返回广告还将被展示的剩余时间。
     * 通过这个接口，开发者可以自行决定是否显示倒计时提示，或者还剩几秒的时候显示倒计时
     *
     * @param millisUntilFinished 剩余毫秒数
     */
    @Override
    public void onADTick(long millisUntilFinished) {
        Timber.e("SplashADTick " + millisUntilFinished + "ms");
        skipView.setVisibility(View.INVISIBLE);
        if (skipView != null) {
            skipView.setText(String.format(SKIP_TEXT, Math.round(millisUntilFinished / 1000f)));
        }
    }

    @Override
    public void onADExposure() {

    }

    @Override
    public void onADLoaded(long l) {
    }

    @Override
    public void onADDismissed() {
        Timber.e("SplashADDismissed");
        next();
    }

    @Override
    public void onNoAD(AdError error) {
        Timber.e(String.format("LoadSplashADFail, eCode=%d, errorMsg=%s", error.getErrorCode(),
                error.getErrorMsg()));
        /** 如果加载广告失败，则直接跳转 */
        this.startActivity(toMainIntent());
        this.finish();
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            this.startActivity(toMainIntent());
            this.finish();
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nextCheck) {
            checkAndRequestPermission();
        }
        nextCheck = false;
        if (canJump) {
            next();
        }
        canJump = true;
    }

    /**
     * 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public View[] getViews() {
        return new View[]{container, skipView, flBottom, adTTHint};
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void displaySplash(final AdModel model) {
        if (model != null) {
            flBottom.setVisibility(View.GONE);
            adTTHint.setVisibility(View.GONE);

            SimpleDraweeView simpleDraweeView = new SimpleDraweeView(this);

            simpleDraweeView.getHierarchy().setBackgroundImage(new ColorDrawable(Color.WHITE));
            simpleDraweeView.getHierarchy().setActualImageScaleType(ScaleType.CENTER_CROP);
            simpleDraweeView.setImageURI(model.imgUrl);

            ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            container.setBackgroundColor(Color.WHITE);
            container.addView(simpleDraweeView, lp);

            simpleDraweeView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.cancelTrack();
//              canJump = true;
//              next();
                    startActivity(toMainIntent());
                    if (!TextUtils.isEmpty(model.linkUrl)) {
                        if (model.linkUrl.endsWith(".apk")) {
                            //如果是apk 直接下载
                            try {
                                DownloadUtils.downloadApk(model.linkUrl, model.getExtValue("title"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            RouterUtils.startTarget(SplashActivity.this, model.linkTarget, model.linkUrl);
                        }
                    }
                    finish();
                }
            });
        }

    }

    private void getDialogTip() {
        final WarningDialog warningDialog = new WarningDialog(SplashActivity.this, "广告信息展示提示");
        warningDialog.setActionDismiss(true);
        warningDialog.setClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                warningDialog.dismiss();
            }
        });
        warningDialog.setButtonText("确定");
        warningDialog.setTitle("广告浏览提示");
        warningDialog.show();
    }

    @Override
    public void onRemainTime(int seconds) {
        if (seconds > 0) {
            skipView.bringToFront();
            skipView.setVisibility(View.VISIBLE);
            skipView.setText(String.format(SKIP_TEXT, seconds));
        } else {
            next();
        }
    }

    @Override
    public void showNoAd() {
        skipView.setVisibility(View.INVISIBLE);
        //splashHolder.setVisibility(View.VISIBLE);
        //splashHolder.setBackgroundColor(ContextCompat.getColor(this,R.color.colorPrimary));
    }

    @Override
    public void onShowAd() {
        bottomLogo.setImageResource(R.drawable.splash_logo);
        ScTimes.adShowTime();
    }

    @Override
    public void toNext() {
        next();
    }

    @Override
    public void toNext(long delay) {

        if (delayJump) {
            return;
        }
        delayJump = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                toNext();
            }
        }, delay);
    }

    @Override
    public Intent toMainIntent() {
//        Intent intent = new Intent(this, MainActivity.class);
//
//        Intent stIntent = getIntent();
//        if (stIntent != null){
//            Bundle extras = stIntent.getExtras();
//            if (extras != null){
//                intent.putExtras(extras);
//            }
//        }
//        return intent;
        return GlobalConfigManager.getInstance().getFlavorConfigure().getMainAct(this, getIntent());
    }

}
